/*
 * Copyright 2024 Tingjin Guo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import worker, { MessageEvents } from '@ohos.worker'

class WorkerManagerClass {
  private fileAppendWorkerMap: Map<string, worker.ThreadWorker> = new Map();
  private listeners: ((e: MessageEvents) => void)[] = [];

  getFileAppendWorker(script: string = './workers/fileAppendWorker.ts'): worker.ThreadWorker {
    if (this.fileAppendWorkerMap.has(script)) {
      return this.fileAppendWorkerMap.get(script);
    }
    const w = new worker.ThreadWorker(script);
    w.onmessage = (e) => {
      this.listeners.forEach(listener => {
        listener(e);
      });
    }
    this.fileAppendWorkerMap.set(script, w);
    return this.fileAppendWorkerMap.get(script);
  }

  registerMessageListener(listener: (e: MessageEvents) => void) {
    if (this.listeners.indexOf(listener) < 0) {
      this.listeners.push(listener);
    }
  }

  terminate() {
    this.listeners = [];
    this.getFileAppendWorker().terminate();
    for(let worker of this.fileAppendWorkerMap){
      worker[1].terminate();
    }
    this.fileAppendWorkerMap.clear();
  }
}

export const WorkerManager = new WorkerManagerClass();